<template>
    <view class="bg-white min-h-screen">
        <!-- 导航栏 -->
        <view class="px-4 py-3 border-b border-slate-100">
            <view class="flex justify-between items-center">
                <button class="p-2" @tap="goBack">
                    <text class="iconfont icon-arrow-left text-slate-800"></text>
                </button>
                <text class="text-lg font-medium text-slate-800">习惯详情</text>
                <button class="p-2" @tap="showOptions">
                    <text class="iconfont icon-more text-slate-800"></text>
                </button>
            </view>
        </view>

        <!-- 习惯头部 -->
        <view class="px-5 pt-6 pb-4">
            <view class="flex items-center">
                <view class="w-14 h-14 rounded-full flex items-center justify-center mr-4"
                    :style="{ backgroundColor: habit.color + '20' }">
                    <text class="iconfont text-2xl" :class="habit.icon" :style="{ color: habit.color }"></text>
                </view>
                <view class="flex-1">
                    <text class="text-xl font-bold text-slate-800">{{ habit.title }}</text>
                    <view class="flex items-center mt-1">
                        <text class="text-sm text-slate-500">{{ habit.frequency }}</text>
                        <view class="w-1 h-1 rounded-full bg-slate-300 mx-2"></view>
                        <text class="text-sm text-slate-500">{{ habit.time }}</text>
                    </view>
                </view>
                <button class="ml-2 px-3 py-1 rounded-lg bg-indigo-500 flex items-center" @tap="editHabit">
                    <text class="text-white text-xs">编辑</text>
                </button>
            </view>

            <view class="mt-4" v-if="habit.description">
                <text class="text-sm text-slate-600">{{ habit.description }}</text>
            </view>
        </view>

        <!-- 完成情况 -->
        <view class="px-5 py-4 bg-slate-50">
            <view class="flex justify-between items-center mb-2">
                <text class="text-sm font-medium text-slate-700">本月完成情况</text>
                <text class="text-sm font-medium text-indigo-600">{{ habit.completionRate }}%</text>
            </view>
            <view class="h-2 bg-slate-200 rounded-full overflow-hidden">
                <view class="h-full rounded-full bg-indigo-500" :style="{ width: `${habit.completionRate}%` }"></view>
            </view>
        </view>

        <!-- 习惯日历 -->
        <view class="px-5 py-6">
            <view class="flex justify-between items-center mb-4">
                <text class="text-base font-medium text-slate-800">习惯日历</text>
                <view class="flex items-center">
                    <button class="p-1" @tap="prevMonth">
                        <text class="iconfont icon-chevron-left text-slate-500"></text>
                    </button>
                    <text class="text-sm text-slate-600 mx-2">{{ currentMonthText }}</text>
                    <button class="p-1" @tap="nextMonth">
                        <text class="iconfont icon-chevron-right text-slate-500"></text>
                    </button>
                </view>
            </view>

            <!-- 日历头部 -->
            <view class="grid grid-cols-7 mb-2">
                <view v-for="day in ['日', '一', '二', '三', '四', '五', '六']" :key="day" class="text-center py-1">
                    <text class="text-xs text-slate-500">{{ day }}</text>
                </view>
            </view>

            <!-- 日历主体 -->
            <view class="grid grid-cols-7 gap-1">
                <view v-for="(day, index) in calendarDays" :key="index"
                    class="aspect-square rounded-lg flex items-center justify-center" :class="getDayClass(day)"
                    @tap="toggleDay(day)">
                    <text class="text-sm" :class="getDayTextClass(day)">
                        {{ day.day > 0 ? day.day : '' }}
                    </text>
                </view>
            </view>
        </view>

        <!-- 统计数据 -->
        <view class="px-5 py-6 border-t border-slate-100">
            <text class="text-base font-medium text-slate-800 mb-4 block">统计数据</text>

            <view class="grid grid-cols-3 gap-4">
                <view class="bg-slate-50 rounded-lg p-4 flex flex-col items-center">
                    <text class="text-xs text-slate-500 mb-1">连续天数</text>
                    <text class="text-xl font-bold text-indigo-600">{{ habit.streak }}</text>
                </view>
                <view class="bg-slate-50 rounded-lg p-4 flex flex-col items-center">
                    <text class="text-xs text-slate-500 mb-1">总完成次数</text>
                    <text class="text-xl font-bold text-indigo-600">{{ habit.totalCompletions }}</text>
                </view>
                <view class="bg-slate-50 rounded-lg p-4 flex flex-col items-center">
                    <text class="text-xs text-slate-500 mb-1">最长连续</text>
                    <text class="text-xl font-bold text-indigo-600">{{ habit.longestStreak }}</text>
                </view>
            </view>
        </view>
    </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';

// 获取路由参数
const habitId = ref('');
onMounted(() => {
    const pages = getCurrentPages();
    const currentPage = pages[pages.length - 1];
    const options = currentPage.$page?.options;
    if (options && options.id) {
        habitId.value = options.id;
        loadHabitData(options.id);
    }
});

// 习惯数据类型
interface CalendarDay {
    day: number;
    month: number;
    year: number;
    isCurrentMonth: boolean;
    isCompleted: boolean;
    isToday: boolean;
}

interface Habit {
    id: string;
    title: string;
    description: string;
    icon: string;
    color: string;
    frequency: string;
    time: string;
    completionRate: number;
    streak: number;
    totalCompletions: number;
    longestStreak: number;
    completedDays: string[]; // ISO日期字符串数组
}

// 习惯数据
const habit = ref<Habit>({
    id: '',
    title: '晨跑',
    description: '每天早上6点进行30分钟的慢跑，保持身体健康和精神焕发。',
    icon: 'icon-running',
    color: '#ef4444',
    frequency: '工作日',
    time: '06:00',
    completionRate: 85,
    streak: 12,
    totalCompletions: 45,
    longestStreak: 21,
    completedDays: [
        '2023-06-01', '2023-06-02', '2023-06-05', '2023-06-06', '2023-06-07',
        '2023-06-08', '2023-06-09', '2023-06-12', '2023-06-13', '2023-06-14',
        '2023-06-15', '2023-06-16', '2023-06-19', '2023-06-20', '2023-06-21'
    ]
});

// 日历相关
const currentDate = ref(new Date());
const calendarDays = ref<CalendarDay[]>([]);

// 当前月份文本
const currentMonthText = computed(() => {
    const year = currentDate.value.getFullYear();
    const month = currentDate.value.getMonth() + 1;
    return `${year}年${month}月`;
});

// 加载习惯数据
const loadHabitData = (id: string) => {
    // 这里应该从数据库或API获取数据
    // 为了演示，我们使用模拟数据
    console.log(`加载习惯数据: ${id}`);
    // 实际应用中这里会有API调用

    // 生成日历数据
    generateCalendar();
};

// 生成日历数据
const generateCalendar = () => {
    const year = currentDate.value.getFullYear();
    const month = currentDate.value.getMonth();

    // 获取当月第一天
    const firstDay = new Date(year, month, 1);
    // 获取当月最后一天
    const lastDay = new Date(year, month + 1, 0);

    // 当月天数
    const daysInMonth = lastDay.getDate();

    // 当月第一天是星期几 (0-6, 0是星期日)
    const firstDayOfWeek = firstDay.getDay();

    // 生成日历数组
    const days: CalendarDay[] = [];

    // 添加上个月的天数
    const prevMonthLastDay = new Date(year, month, 0).getDate();
    for (let i = 0; i < firstDayOfWeek; i++) {
        const day = prevMonthLastDay - firstDayOfWeek + i + 1;
        days.push({
            day,
            month: month - 1 < 0 ? 11 : month - 1,
            year: month - 1 < 0 ? year - 1 : year,
            isCurrentMonth: false,
            isCompleted: false,
            isToday: false
        });
    }

    // 添加当月的天数
    const today = new Date();
    for (let i = 1; i <= daysInMonth; i++) {
        const date = new Date(year, month, i);
        const dateString = date.toISOString().split('T')[0];

        days.push({
            day: i,
            month,
            year,
            isCurrentMonth: true,
            isCompleted: habit.value.completedDays.includes(dateString),
            isToday:
                today.getDate() === i &&
                today.getMonth() === month &&
                today.getFullYear() === year
        });
    }

    // 添加下个月的天数
    const remainingDays = 42 - days.length; // 6行7列 = 42
    for (let i = 1; i <= remainingDays; i++) {
        days.push({
            day: i,
            month: month + 1 > 11 ? 0 : month + 1,
            year: month + 1 > 11 ? year + 1 : year,
            isCurrentMonth: false,
            isCompleted: false,
            isToday: false
        });
    }

    calendarDays.value = days;
};

// 获取日期样式类
const getDayClass = (day: CalendarDay) => {
    if (!day.isCurrentMonth) return 'opacity-30';
    if (day.isToday) return 'bg-indigo-100';
    if (day.isCompleted) return 'bg-green-100';
    return '';
};

// 获取日期文本样式类
const getDayTextClass = (day: CalendarDay) => {
    if (!day.isCurrentMonth) return 'text-slate-400';
    if (day.isToday) return 'text-indigo-600 font-bold';
    if (day.isCompleted) return 'text-green-600';
    return 'text-slate-800';
};

// 切换日期完成状态
const toggleDay = (day: CalendarDay) => {
    if (!day.isCurrentMonth) return;

    // 构建日期字符串
    const date = new Date(day.year, day.month, day.day);
    const dateString = date.toISOString().split('T')[0];

    // 切换完成状态
    if (day.isCompleted) {
        // 移除完成日期
        habit.value.completedDays = habit.value.completedDays.filter(d => d !== dateString);
    } else {
        // 添加完成日期
        habit.value.completedDays.push(dateString);
    }

    // 更新日历
    day.isCompleted = !day.isCompleted;

    // 更新统计数据
    updateStats();
};

// 更新统计数据
const updateStats = () => {
    // 计算完成率
    const daysInMonth = new Date(
        currentDate.value.getFullYear(),
        currentDate.value.getMonth() + 1,
        0
    ).getDate();

    const currentMonth = currentDate.value.getMonth();
    const currentYear = currentDate.value.getFullYear();

    // 当月完成的天数
    const completedThisMonth = habit.value.completedDays.filter(dateString => {
        const date = new Date(dateString);
        return date.getMonth() === currentMonth && date.getFullYear() === currentYear;
    }).length;

    // 计算完成率
    habit.value.completionRate = Math.round((completedThisMonth / daysInMonth) * 100);

    // 计算总完成次数
    habit.value.totalCompletions = habit.value.completedDays.length;

    // 计算连续天数和最长连续天数
    // 这里需要更复杂的逻辑，简化处理
    habit.value.streak = 12;
    habit.value.longestStreak = 21;
};

// 上个月
const prevMonth = () => {
    currentDate.value = new Date(
        currentDate.value.getFullYear(),
        currentDate.value.getMonth() - 1,
        1
    );
    generateCalendar();
};

// 下个月
const nextMonth = () => {
    currentDate.value = new Date(
        currentDate.value.getFullYear(),
        currentDate.value.getMonth() + 1,
        1
    );
    generateCalendar();
};

// 编辑习惯
const editHabit = () => {
    uni.navigateTo({
        url: `/subPages/habit/add?id=${habit.value.id}`
    });
};

// 显示选项菜单
const showOptions = () => {
    uni.showActionSheet({
        itemList: ['编辑习惯', '删除习惯'],
        success: (res) => {
            if (res.tapIndex === 0) {
                // 编辑习惯
                editHabit();
            } else if (res.tapIndex === 1) {
                // 删除习惯
                uni.showModal({
                    title: '删除习惯',
                    content: '确定要删除这个习惯吗？所有相关数据将被永久删除。',
                    confirmColor: '#ef4444',
                    success: (res) => {
                        if (res.confirm) {
                            // 执行删除操作
                            uni.showToast({
                                title: '删除成功',
                                icon: 'success',
                                success: () => {
                                    setTimeout(() => {
                                        goBack();
                                    }, 1500);
                                }
                            });
                        }
                    }
                });
            }
        }
    });
};

// 返回上一页
const goBack = () => {
    uni.navigateBack();
};
</script>

<style>
/* 添加额外的图标 */
.icon-arrow-left:before {
    content: '\e628';
}

.icon-more:before {
    content: '\e639';
}

.icon-chevron-left:before {
    content: '\e62a';
}

.icon-chevron-right:before {
    content: '\e629';
}

.icon-running:before {
    content: '\e640';
}
</style>